<template>
    <el-container>
        <el-main class="blog-preview-list-container">
            <BlogPreviewComponent v-for="(blogPreview, index) in blogPreviewList" :key="blogPreview.id"
                :blogPreview="blogPreview"></BlogPreviewComponent>
        </el-main>
        <el-footer style="display: flex;justify-content: center;">
            <el-pagination background layout="prev, pager, next" v-model:current-page="currentPage"
                :page-count="pageCount" :pager-count=pagerCount />
        </el-footer>
    </el-container>
</template>

<script setup lang="ts">
import { defaultblogSearchQuery } from "@/defaults/searchDefault";
import { BlogPreview } from "@/types/blogType";
import { PageResultDto } from "@/types/commonType";
import { BlogSearchData, BlogSearchQuery, BlogSearchType } from "@/types/serchType";
import { tokenAxios } from "@/utils/tokenAxiosUtils";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
const blogPreviewList = ref<BlogPreview[]>();

const currentPage = ref(1);
const pageCount = ref(1);
/**设置最大页码按钮数。 页码按钮的数量，当总页数超过该值时会折叠 */
const pagerCount = ref(11);

const blogSearchQuery = computed(() => {
    return {
        searchType: route.query.searchType as BlogSearchType || defaultblogSearchQuery.searchType,
        keyWords: route.query.searchKeyWord as string || defaultblogSearchQuery.searchKeyWord,
        pageIndex: route.query.searchPageIndex as unknown as number || defaultblogSearchQuery.searchPageIndex
    } as BlogSearchQuery
});

const blogSearchAxios = async () => {
    switch (blogSearchQuery.value.searchType) {
        case BlogSearchType.NoSearch:
            return tokenAxios.get(`/blog/getPreview/${currentPage.value}`);
        case BlogSearchType.GetSearch:
            const blogsearchData: BlogSearchData = {
                keywordList: blogSearchQuery.value.keyWords.split(/\s+/),
                pageIndex: blogSearchQuery.value.pageIndex
            }
            return tokenAxios.post(`/blog/getSearch`, blogsearchData);
    }
}

const fetchArticle = async () => {
    try {
        const res = await blogSearchAxios();
        console.log(res);
        ({ content: blogPreviewList.value, totalPages: pageCount.value } = res.data as PageResultDto<BlogPreview>);
        console.log(res.data);
    }
    catch (error) {
        console.error("获取博客数据失败", error)
    }
}

onMounted(() => {
    fetchArticle();
})

watch(() => currentPage.value, (newPage) => {
    console.log('页码变化:', newPage)
    blogSearchQuery.value.pageIndex = newPage;
    fetchArticle();
})

watch(() => blogSearchQuery.value, (newQuery) => {
    console.log('查询变化:', blogSearchQuery.value, newQuery)
    fetchArticle();
})
</script>

<style scoped>
.blog-preview-list-container {
    display: flex;
    align-items: center;
    flex-direction: column;
    gap: 10px;
}
</style>